import React, { useState, Fragment } from 'react'
import { Card, Form, Input, Select, Checkbox, Button, Space, message } from 'antd'
import { useRequest, useMount } from 'ahooks'
import StepFlow from '@/pages/Dashboard/common/StepFlow'
import AuthComponent from '@/components/AuthComponent'

import { listConsortiums, listChannelOfConsortium, createCommunicationChain, listDeployedChannels } from '@/pages/Dashboard/components/CrossChain/service'

const CheckboxGroup = Checkbox.Group
const { TextArea } = Input

const NewCommunicationChain = ({ history }) => {
  const [form] = Form.useForm()
  const [useBaas, setUseBaas] = useState(true)
  const [consortiums, setConsortiums] = useState([])
  const [channels, setChannels] = useState([])
  const [deployedChannels, setDeployedChannels] = useState([])
  const { loading: loadingConsortiums, run: loadConsortium } = useRequest(listConsortiums, { manual: true })
  const { loading: loadingChannels, run: loadChannel } = useRequest(listChannelOfConsortium, { manual: true })
  const { loading: loadingDeployedChannels, run: loadDeployedChannels } = useRequest(listDeployedChannels, { manual: true })
  const { loading: creatingChain, run: newCommunicationChain } = useRequest(createCommunicationChain, { manual: true })
  const steps = [
    {
      key: 'unify',
      img: require('@/images/fabric/2.svg'),
      number: '1.',
      text: '创建通讯链',
      iconW: 40,
      iconH: 30,
      changeLink: true,
      bcsLink: '/dashboard/fabric/createLeague',
    },
    {
      key: 'deploy',
      img: require('@/images/fabric/5.svg'),
      number: '2.',
      text: '部署合约',
      iconW: 30,
      iconH: 30,
      stateKey: '2',
    },
    {
      key: 'requestCrossChain',
      img: require('@/images/fabric/1.svg'),
      number: '3.',
      text: '申请跨链通讯',
      iconW: 30,
      iconH: 30,
      changeLink: true,
      bcsLink: '/dashboard/fabric/createOrganization',
    },
    {
      key: 'voteCrossApplications',
      img: require('@/images/fabric/6.svg'),
      number: '4.',
      text: '投票跨链申请',
      iconW: 30,
      iconH: 30,
      stateKey: '3',
    },
  ]
  const initialValues = {
    baas_management: true,
    permission: ['sender', 'receiver'],
  }
  const permissions = [
    { label: '发送跨链交易', value: 'sender' },
    { label: '接受跨链交易', value: 'receiver' },
  ]
  const queryConsortiums = async() => {
    try {
      const res = await loadConsortium()
      const { data: consortiums } = res
      setConsortiums(consortiums)
    } catch (e) {
      console.error(e)
    }
  }
  const queryChannels = async(consortiumId) => {
    try {
      const res = await loadChannel(consortiumId)
      const deployRes = await loadDeployedChannels({
        consortiumId,
      })
      const { data: { channels }} = res
      const { data: { data: deployedChannels }} = deployRes
      setChannels(channels)
      const newDeployedChannels = deployedChannels.map((channel) => channel.id)
      setDeployedChannels(newDeployedChannels)
    } catch (e) {
      console.error(e)
    }
  }
  useMount(() => {
    queryConsortiums()
  })
  const onFinish = async(values) => {
    const { permission } = values
    const canSend = permission.indexOf('sender') >= 0
    const acceptable = permission.indexOf('receiver') >= 0
    try {
      const res = await newCommunicationChain({
        ...values,
        can_send: canSend,
        acceptable,
      })
      const { data: { success }} = res
      if (success) {
        message.success(`创建通讯链成功 ${values.name}`)
        history.goBack()
      }
    } catch (e) {
      message.error(`创建通讯链失败 ${values.name}`)
    }
  }
  const onConsortiumChange = (value) => {
    form.setFieldsValue({ channel: null })
    queryChannels(value)
  }
  return (
    <div>
      <StepFlow title="通讯链创建流程" steps={steps} />
      <Card>
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 12 }}
          layout="horizontal"
          initialValues={initialValues}
          onFinish={onFinish}
        >
          <Form.Item label="是否Baas管理" name="baas_management">
            <Select onChange={(value) => setUseBaas(value)}>
              <Select.Option value={true}>是</Select.Option>
              <Select.Option value={false}>否</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="通讯链类型">
            <Input disabled placeholder="Hyperledger Fabric" style={{ width: '100%' }} />
          </Form.Item>
          {useBaas === true &&
            <Fragment>
              <Form.Item
                label="所属联盟"
                name="consortium_id"
                rules={[{ required: true, message: '请选择联盟' }]}
              >
                <Select
                  onChange={onConsortiumChange}
                  loading={loadingConsortiums}
                  placeholder="请选择所属联盟"
                >
                  {consortiums.map((consortium) => <Select.Option key={consortium.id} value={consortium.id} disabled={consortium.status !== 'SUCCESS'}>{consortium.display_name}</Select.Option>)}
                </Select>
              </Form.Item>
              <Form.Item
                label="所属通道"
                name="channel_id"
                rules={[{ required: true, message: '请选择通道' }]}
              >
                <Select loading={loadingChannels || loadingDeployedChannels} placeholder="请选择所属通道">
                  {channels.map((channel) => <Select.Option key={channel.id} value={channel.id} disabled={deployedChannels.indexOf(channel.id) >= 0}>{channel.name}</Select.Option>)}
                </Select>
              </Form.Item>
            </Fragment>
          }
          <Form.Item
            label="通讯链名称"
            name="name"
            rules={[{ required: true, message: '请输入通讯链名称' }]}
          >
            <Input placeholder="请填写通讯链名称 (15个字符以内)" maxLength={15} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            label="通讯链权限"
            name="permission"
            rules={[{ required: true, message: '请选择通讯链权限' }]}
          >
            <CheckboxGroup disabled options={permissions} />
          </Form.Item>
          {useBaas === false &&
            <Form.Item label="适配器接口地址" name="adapter_address" rules={
              [
                {
                  required: true,
                  message: '',
                },
              ]
            }>
              <Input placeholder="请填写接口地址，例如：http://192.168.2.217:8000" style={{ width: '100%' }} />
            </Form.Item>
          }
          <Form.Item label="适配器用户名"
            name="adapter_username"
            rules={[
              {
                required: true,
                message: '请填写适配器用户名',
              },
            ]}
          >
            <Input placeholder="请填写" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="适配器密码"
            name="adapter__pwd"
            rules={
              [
                {
                  required: true,
                  message: '请填写适配器密码',
                },
              ]
            }
          >
            <Input.Password placeholder="请填写" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="description" label="描述" rules={
            [
              {
                required: true,
                message: '请输入描述（不超过50个字符）',
              },
            ]
          }>
            <TextArea rows={4} placeholer="请输入描述（不超过50个字符）" maxLength={50} />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 6, span: 12 }}>
            <Space>
              <Button type="primary" htmlType="submit" loading={creatingChain}>
                确定
              </Button>
              <Button onClick={() => history.goBack()}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default AuthComponent('cross-chain-communication-create')(NewCommunicationChain)
